#!/usr/bin/env python3
"""
MD2PPT Java集成快速启动脚本
一键体验完整的Python-Java集成功能
"""

import sys
import json
import time
from pathlib import Path
import logging

def setup_logging():
    """设置日志"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )
    return logging.getLogger(__name__)

def check_environment():
    """检查环境依赖"""
    logger = logging.getLogger(__name__)
    
    print("🔍 检查环境依赖...")
    
    # 检查Python版本
    if sys.version_info < (3, 8):
        print("❌ Python版本过低，需要3.8+")
        return False
    print(f"✅ Python {sys.version_info.major}.{sys.version_info.minor}")
    
    # 检查Java
    import subprocess
    try:
        result = subprocess.run(['java', '-version'], capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ Java环境可用")
        else:
            print("⚠️ Java环境检查失败，某些功能可能不可用")
    except FileNotFoundError:
        print("⚠️ 未找到Java，请安装JDK 17+")
    
    # 检查依赖包
    try:
        import psutil
        print("✅ psutil已安装")
    except ImportError:
        print("⚠️ 缺少psutil包，性能监控功能受限")
        print("   安装: pip install psutil")
    
    # 检查Java CLI JAR
    jar_path = Path("java-cli/target/md2ppt-aspose-cli.jar")
    if jar_path.exists():
        print("✅ Java CLI JAR文件存在")
    else:
        print("⚠️ 未找到Java CLI JAR文件")
        print("   构建: cd java-cli && mvn clean package")
    
    return True

def create_demo_config():
    """创建演示配置文件"""
    config = {
        "metadata": {
            "title": "MD2PPT集成演示",
            "author": "Python-Java集成系统",
            "version": "2.0.0",
            "created": "2024-01-01"
        },
        "settings": {
            "theme": "default",
            "quality": "HIGH",
            "timeout_seconds": 300,
            "animation_engine": "ASPOSE_JAVA",
            "fallback_engine": "PYTHON_PPTX"
        },
        "slides": [
            {
                "index": 1,
                "title": "欢迎使用MD2PPT Java集成",
                "content": [
                    {
                        "type": "text",
                        "data": {
                            "text": "🎉 Python-Java集成系统启动成功！\n\n特性：\n• 强大的动画效果支持\n• 多引擎智能回退\n• 企业级安全保障\n• 实时性能监控"
                        },
                        "position": {
                            "x": 100, "y": 200,
                            "width": 800, "height": 300
                        },
                        "style": {
                            "font_size": 18,
                            "font_family": "Arial",
                            "color": "#333333"
                        }
                    }
                ],
                "animations": [
                    {
                        "target_element": "🎉 Python-Java集成系统启动成功！",
                        "effect_type": "fade_in",
                        "timing": {
                            "start_delay": 0.5,
                            "duration": 2.0,
                            "repeat_count": 1,
                            "auto_reverse": False
                        },
                        "properties": {
                            "direction": "from_left",
                            "speed": "medium"
                        }
                    }
                ]
            },
            {
                "index": 2,
                "title": "技术架构",
                "content": [
                    {
                        "type": "text",
                        "data": {
                            "text": "架构组件：\n\n🐍 Python端：\n• Markdown解析\n• 配置生成\n• 基础PPT创建\n\n☕ Java端：\n• Aspose.Slides动画引擎\n• Apache POI回退支持\n• 150+ 动画效果"
                        },
                        "position": {
                            "x": 100, "y": 150,
                            "width": 800, "height": 400
                        }
                    }
                ],
                "animations": [
                    {
                        "target_element": "🐍 Python端：",
                        "effect_type": "fly_in",
                        "timing": {
                            "start_delay": 0.0,
                            "duration": 1.5,
                            "repeat_count": 1
                        },
                        "properties": {
                            "direction": "from_left"
                        }
                    },
                    {
                        "target_element": "☕ Java端：",
                        "effect_type": "fly_in",
                        "timing": {
                            "start_delay": 1.0,
                            "duration": 1.5,
                            "repeat_count": 1
                        },
                        "properties": {
                            "direction": "from_right"
                        }
                    }
                ]
            },
            {
                "index": 3,
                "title": "感谢使用",
                "content": [
                    {
                        "type": "text",
                        "data": {
                            "text": "🚀 MD2PPT v2.0\nPython-Java集成版\n\n让演示文稿创建更简单\n让动画效果更精彩！"
                        },
                        "position": {
                            "x": 200, "y": 250,
                            "width": 600, "height": 200
                        },
                        "style": {
                            "font_size": 24,
                            "color": "#2196F3",
                            "text_align": "center"
                        }
                    }
                ],
                "animations": [
                    {
                        "target_element": "🚀 MD2PPT v2.0",
                        "effect_type": "pulse",
                        "timing": {
                            "start_delay": 1.0,
                            "duration": 3.0,
                            "repeat_count": 2,
                            "auto_reverse": True
                        }
                    }
                ]
            }
        ]
    }
    
    config_path = Path("quick_start_config.json")
    with open(config_path, 'w', encoding='utf-8') as f:
        json.dump(config, f, ensure_ascii=False, indent=2)
    
    print(f"📝 演示配置文件已创建: {config_path}")
    return config_path

def test_integration():
    """测试集成功能"""
    logger = logging.getLogger(__name__)
    
    try:
        # 导入集成模块
        from md2ppt.integration import JavaBridge
        print("✅ Python集成模块导入成功")
        
        # 初始化桥接器
        bridge = JavaBridge()
        print("✅ Java桥接器初始化成功")
        
        # 检查Java环境
        java_status = bridge.check_java_engines()
        if java_status.get('available'):
            print("✅ Java CLI环境检查通过")
            return bridge
        else:
            print(f"⚠️ Java CLI不可用: {java_status.get('reason', '未知原因')}")
            print("   这可能是因为：")
            print("   1. 未构建Java CLI: cd java-cli && mvn clean package")
            print("   2. Java版本不兼容: 需要JDK 17+")
            print("   3. JAR文件路径错误")
            return bridge  # 仍然返回bridge以便测试Python功能
            
    except ImportError as e:
        print(f"❌ 导入失败: {e}")
        print("   请确保Python路径正确，或者手动添加模块路径")
        return None

def run_generation_test(bridge, config_path):
    """运行生成测试"""
    logger = logging.getLogger(__name__)
    
    output_path = Path("quick_start_output.pptx")
    
    print("\n🔄 开始生成演示文稿...")
    print(f"   配置文件: {config_path}")
    print(f"   输出文件: {output_path}")
    
    try:
        # 尝试Java生成
        result = bridge.generate_with_java(
            config_path=config_path,
            output_path=output_path,
            quality="HIGH",
            verbose=True,
            timeout=120
        )
        
        print("\n📊 生成结果:")
        print(f"   成功: {'✅' if result['success'] else '❌'}")
        print(f"   消息: {result['message']}")
        
        if result['success']:
            if 'output_file' in result:
                print(f"   输出文件: {result['output_file']['path']}")
                print(f"   文件大小: {result['output_file']['size']} bytes")
            print(f"   处理时间: {result['processing_time']:.2f}秒")
            print(f"   请求ID: {result.get('request_id', 'N/A')}")
        else:
            print(f"   错误详情: {result.get('stderr', 'N/A')}")
            if result.get('java_available') == False:
                print("   建议: 检查Java环境和JAR文件")
        
        return result
        
    except Exception as e:
        print(f"❌ 生成过程异常: {e}")
        logger.error("生成测试失败", exc_info=True)
        return {"success": False, "error": str(e)}

def show_performance_summary(bridge):
    """显示性能摘要"""
    try:
        summary = bridge.performance_manager.get_performance_summary()
        
        if summary.get('total_requests', 0) > 0:
            print("\n📈 性能摘要:")
            print(f"   总请求数: {summary['total_requests']}")
            print(f"   成功率: {summary['success_rate_percent']}%")
            print(f"   平均处理时间: {summary['avg_processing_time_seconds']:.2f}秒")
            
            # 检查性能问题
            issues = bridge.performance_manager.detect_performance_issues()
            if issues:
                print(f"   ⚠️ 性能问题: {', '.join(issues)}")
                
                # 显示优化建议
                recommendations = bridge.performance_manager.optimize_recommendations()
                if recommendations:
                    print("   💡 优化建议:")
                    for rec in recommendations[:3]:  # 显示前3个建议
                        print(f"      • {rec}")
        else:
            print("\n📈 暂无性能数据")
            
    except Exception as e:
        print(f"⚠️ 性能监控异常: {e}")

def cleanup_files():
    """清理临时文件"""
    files_to_cleanup = [
        "quick_start_config.json",
        "quick_start_output.pptx"
    ]
    
    cleaned = 0
    for file_path in files_to_cleanup:
        path = Path(file_path)
        if path.exists():
            path.unlink()
            cleaned += 1
    
    if cleaned > 0:
        print(f"\n🧹 已清理 {cleaned} 个临时文件")

def main():
    """主函数"""
    print("🚀 MD2PPT Python-Java集成快速启动")
    print("=" * 50)
    
    logger = setup_logging()
    
    try:
        # 1. 环境检查
        if not check_environment():
            print("\n❌ 环境检查失败，请修复后重试")
            return 1
        
        # 2. 创建演示配置
        config_path = create_demo_config()
        
        # 3. 测试集成
        print("\n🔧 测试集成功能...")
        bridge = test_integration()
        
        if bridge is None:
            print("\n❌ 集成测试失败")
            return 1
        
        # 4. 运行生成测试
        result = run_generation_test(bridge, config_path)
        
        # 5. 显示性能摘要
        show_performance_summary(bridge)
        
        # 6. 显示使用指南
        print("\n📚 接下来你可以：")
        if result.get('success'):
            print("   1. 查看生成的演示文稿: quick_start_output.pptx")
            print("   2. 修改配置文件测试不同效果")
            print("   3. 阅读完整使用指南: USAGE_GUIDE.md")
        else:
            print("   1. 检查Java环境: java -version")
            print("   2. 构建Java CLI: cd java-cli && mvn clean package")
            print("   3. 查看故障排除指南: USAGE_GUIDE.md")
        
        print("   4. 查看集成文档: java-cli/INTEGRATION_GUIDE.md")
        print("   5. 运行性能测试: python integration_example.py")
        
        # 7. 清理（可选）
        print(f"\n❓ 是否清理临时文件？(y/N): ", end="")
        try:
            response = input().strip().lower()
            if response in ['y', 'yes']:
                cleanup_files()
        except KeyboardInterrupt:
            print("\n")
        
        print("\n✨ 快速启动完成!")
        return 0 if result.get('success') else 1
        
    except KeyboardInterrupt:
        print("\n\n⚠️ 用户中断")
        return 1
    except Exception as e:
        logger.error("快速启动失败", exc_info=True)
        print(f"\n❌ 意外错误: {e}")
        return 1

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)